# Author: tang
# Date: 2024-05-17
# Description: 各设备类型采集程序
# Previous version: 2.x
# Modification:
#     2024-11-19: 融合新架构3.0，带图谱的设备新增字段

# 标准库
import json
import math
import time
import logging
import binascii
import datetime

# 自建库
import public_func as pf
from common_vars import DeviceSix

# logging.basicConfig(format='%(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s: %(message)s',
#                     level=logging.DEBUG)  # todo test

EIGHT_CHANNEL_PAPA = {}  # 八通道参数  {'device_code':{'pa1_value':pa1_value,...,'sp3_value':sp3_value},...}
THREE_CHANNEL_PAPA = {}  # 三通道参数  {'device_code':{'pa1_value':pa1_value,...,'sp3_value':sp3_value},...}
UHF_PAPA = {}  # 429三合一UHF参数  {'device_code':{'uhf_base':uhf_base,'uhf_db':uhf_db,...},...}
CIRCU_DECIMAL_PARA = {}  # 环流小数处理方式  {'device_code':0,...}
DEV27_CONNECT_INFO = {}  # 南网27多合一设备tcp连接信息 {'device_code':{'first_time':1722392456.3416467, 'count':1},...}


def eight_channel_collect(redis_conn, cli_sk, device_code, slave_id, device_type, temp_numb, dev_para_list):
    """
    八通道采集程序-01
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        temp_numb: 温度传感器数量(int)
        dev_para_list: 已读取过参数的设备

    Returns: None

    """
    # 八通道参数默认值
    pa1_value = 470  # db系数
    pa2_value = 470
    pa3_value = 470
    bv1_value = 500  # 基值
    bv2_value = 500
    bv3_value = 500
    abv1_value = 0  # 附加基值
    abv2_value = 0
    abv3_value = 0
    sp1_value = 100  # 传感系数
    sp2_value = 100
    sp3_value = 100

    crc_flag = True
    if device_code not in dev_para_list:  # 该设备未读取过参数
        para_list = []  # [{'address': '0001', 'value': 5}, {'address': '0002', 'value': 625}, ...]
        for n in range(3):
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x01, 0x00, 0x60)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, recv_data))
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                for i in range(0, 96):
                    address = '%04X' % (i + 1)
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    if address in {'0024', '0025', '002E', '004C'}:
                        if value >= 32768:  # 0-65535转有符号-32768至32768
                            value -= 65536
                    para_list.append({'address': address, 'value': value})

                    if address == '0007':
                        pa1_value = value
                    elif address == '000C':
                        pa2_value = value
                    elif address == '0029':
                        pa3_value = value
                    elif address == '0006':
                        bv1_value = value
                    elif address == '000B':
                        bv2_value = value
                    elif address == '0028':
                        bv3_value = value
                    elif address == '0024':
                        abv1_value = value
                    elif address == '0025':
                        abv2_value = value
                    elif address == '002E':
                        abv3_value = value
                    elif address == '000A':
                        sp1_value = value
                    elif address == '000F':
                        sp2_value = value
                    elif address == '002C':
                        sp3_value = value

                EIGHT_CHANNEL_PAPA[device_code] = {'pa1_value': pa1_value, 'pa2_value': pa2_value,
                                                   'pa3_value': pa3_value,
                                                   'bv1_value': bv1_value, 'bv2_value': bv2_value,
                                                   'bv3_value': bv3_value,
                                                   'abv1_value': abv1_value, 'abv2_value': abv2_value,
                                                   'abv3_value': abv3_value,
                                                   'sp1_value': sp1_value, 'sp2_value': sp2_value,
                                                   'sp3_value': sp3_value}
                break
            else:
                if n == 2:
                    crc_flag = False

        logging.debug((device_code, para_list))
        logging.debug((device_code, pa1_value, pa2_value, pa3_value,
                       bv1_value, bv2_value, bv3_value,
                       abv1_value, abv2_value, abv3_value,
                       sp1_value, sp2_value, sp3_value))

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x05, 0x00, 0x00, 0x02)  # 读取设备编码
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                dev_ins_id = int.from_bytes(recv_data[3:7], byteorder='big')
            else:
                dev_ins_id = ''

            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x21, 0x00, 0x01)  # 读取波特率
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                data = int.from_bytes(recv_data[3:5], byteorder='big')
                if data == 85:  # 0x55
                    baudrate = 9600
                elif data == 170:  # 0xAA
                    baudrate = 115200
                else:
                    baudrate = ''
            else:
                baudrate = ''

            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x05, 0x10, 0x00, 0x01)  # 读取程序版本号
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                soft_version = str(binascii.hexlify(recv_data[3:5]), encoding='utf-8')
            else:
                soft_version = ''

            dev_info = {'device_inside_id': dev_ins_id, 'baudrate': baudrate, 'software_version': soft_version,
                        'hardware_version': '', 'lf': 'ch2', 'mf': 'ch1', 'hf': 'ch3'}
            logging.debug((device_code, dev_info))

            para_1 = {'device_info': dev_info, 'para_dictionary_table': para_list}  # para_dictionary_table
            para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
            para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            para_json = json.dumps(para_dict)
            logging.debug((device_code,
                           para_json))  # {"data_type": "parameter", "data": "{\"device_type\": \"01\", \"device_code\": \"gz0124010001\", \"data\": \"{\\\"device_info\\\": {\\\"device_inside_id\\\": 202811, \\\"baudrate\\\": 115200, \\\"software_version\\\": \\\"2366\\\", \\\"hardware_version\\\": \\\"\\\", \\\"lf\\\": \\\"ch3\\\", \\\"mf\\\": \\\"ch1\\\", \\\"hf\\\": \\\"ch2\\\"}, \\\"para_dictionary_table\\\": [{\\\"address\\\": \\\"0001\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0002\\\", \\\"value\\\": 625}, {\\\"address\\\": \\\"0003\\\", \\\"value\\\": 3}, {\\\"address\\\": \\\"0004\\\", \\\"value\\\": 8}, {\\\"address\\\": \\\"0005\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0006\\\", \\\"value\\\": 363}, {\\\"address\\\": \\\"0007\\\", \\\"value\\\": 450}, {\\\"address\\\": \\\"0008\\\", \\\"value\\\": 20}, {\\\"address\\\": \\\"0009\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"000A\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"000B\\\", \\\"value\\\": 325}, {\\\"address\\\": \\\"000C\\\", \\\"value\\\": 508}, {\\\"address\\\": \\\"000D\\\", \\\"value\\\": 20}, {\\\"address\\\": \\\"000E\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"000F\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"0010\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"0011\\\", \\\"value\\\": 10}, {\\\"address\\\": \\\"0012\\\", \\\"value\\\": 500}, {\\\"address\\\": \\\"0013\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"0014\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"0015\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"0016\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0017\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0018\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0019\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001A\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001B\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001C\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001D\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001E\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001F\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"0020\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"0021\\\", \\\"value\\\": 170}, {\\\"address\\\": \\\"0022\\\", \\\"value\\\": 900}, {\\\"address\\\": \\\"0023\\\", \\\"value\\\": 650}, {\\\"address\\\": \\\"0024\\\", \\\"value\\\": 190}, {\\\"address\\\": \\\"0025\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0026\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0027\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0028\\\", \\\"value\\\": 433}, {\\\"address\\\": \\\"0029\\\", \\\"value\\\": 508}, {\\\"address\\\": \\\"002A\\\", \\\"value\\\": 20}, {\\\"address\\\": \\\"002B\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"002C\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"002D\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"002E\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"002F\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0030\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0031\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0032\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0033\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0034\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0035\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0036\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0037\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"0038\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"0039\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003A\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003B\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003C\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003D\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003E\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003F\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0040\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0041\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0042\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0043\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0044\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0045\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0046\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0047\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"0048\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"0049\\\", \\\"value\\\": 160}, {\\\"address\\\": \\\"004A\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"004B\\\", \\\"value\\\": 43690}, {\\\"address\\\": \\\"004C\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"004D\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"004E\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"004F\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0050\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0051\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0052\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0053\\\", \\\"value\\\": 10}, {\\\"address\\\": \\\"0054\\\", \\\"value\\\": 10}, {\\\"address\\\": \\\"0055\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0056\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"0057\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0058\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0059\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"005A\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"005B\\\", \\\"value\\\": 30}, {\\\"address\\\": \\\"005C\\\", \\\"value\\\": 3}, {\\\"address\\\": \\\"005D\\\", \\\"value\\\": 30}, {\\\"address\\\": \\\"005E\\\", \\\"value\\\": 3}, {\\\"address\\\": \\\"005F\\\", \\\"value\\\": 30}, {\\\"address\\\": \\\"0060\\\", \\\"value\\\": 3}]}\"}", "update_time": "2024-05-20 18:05:46"}
            redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
            logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

    logging.debug(EIGHT_CHANNEL_PAPA)
    logging.debug((device_code, crc_flag))
    if crc_flag and device_code in EIGHT_CHANNEL_PAPA:
        pd_data = []  # 局放数据
        temp_data = []  # 温度数据
        for channel in range(1, 9):  # 读取八通道数据
            crc_flag = True  # crc校验标志
            amplitude = 0
            frequency = 0
            energy = 0
            alarm_value = 0
            ch1_amplitudeArray = []
            ch2_amplitudeArray = []
            ch3_amplitudeArray = []
            phaseArray = []
            cycleArray = []

            address_l = (channel - 1) * 6
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x01, address_l, 0x00, 0x06)  # 读取幅值、频次等数据
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, "recv_data: " + ''.join(['%02X ' % b for b in recv_data])))
                amplitude = int.from_bytes(recv_data[3:5], byteorder='big')  # 幅值
                frequency = int.from_bytes(recv_data[5:7], byteorder='big')  # 频次
                energy = int.from_bytes(recv_data[7:11], byteorder='big')  # 能量
                alarm_value = int.from_bytes(recv_data[11:13], byteorder='big')  # 报警
            else:
                crc_flag = False

            if crc_flag:
                if frequency > 0:  # 读取谱图
                    address_l = channel + 1
                    atlas_cmd = pf.modbus_command(slave_id, 0x05, 0x02, address_l, 0xFF, 0x00)
                    logging.debug(
                        (device_code, 'dev_id:' + str(slave_id), 'channel:' + str(channel),
                         'dev_type:' + device_type,
                         "atlas_cmd: " + ''.join(['%02X ' % b for b in atlas_cmd])))
                    cli_sk.send(atlas_cmd)
                    atlas_data = pf.data_receive(cli_sk)
                    logging.debug((device_code, 'dev_id:' + str(slave_id), 'channel:' + str(channel),
                                   "atlas_data: " + ''.join(
                                       ['%02X ' % b for b in atlas_data])))
                    if atlas_data:
                        data_len = int.from_bytes(atlas_data[5:7],
                                                  byteorder='big')  # 数据长度
                        logging.debug((device_code, 'dev_id:' + str(slave_id),
                                       'channel:' + str(channel), data_len))
                        group_len = (data_len - 9) // 10  # 共多少组数据
                        data = atlas_data[7:data_len - 2]  # 谱图数据
                        logging.debug(
                            (device_code, 'dev_id:' + str(slave_id), 'channel:' + str(channel),
                             "data recv:" + ''.join(['%02X ' % b for b in data])))
                        for num in range(group_len):
                            ch1_amp = int.from_bytes(data[num * 10 + 0:num * 10 + 2],
                                                     byteorder='big')  # 原幅值
                            cal_ch1_amp = float('%.2f' % ((10 ** ((ch1_amp - (
                                    EIGHT_CHANNEL_PAPA[device_code]['bv1_value'] + EIGHT_CHANNEL_PAPA[device_code][
                                'abv1_value'])) / EIGHT_CHANNEL_PAPA[device_code]['pa1_value'])) *
                                                          EIGHT_CHANNEL_PAPA[device_code][
                                                              'sp1_value'] / 100))  # 计算后幅值(Pc)
                            ch2_amp = int.from_bytes(data[num * 10 + 2:num * 10 + 4],
                                                     byteorder='big')
                            cal_ch2_amp = float('%.2f' % ((10 ** ((ch2_amp - (
                                    EIGHT_CHANNEL_PAPA[device_code]['bv2_value'] + EIGHT_CHANNEL_PAPA[device_code][
                                'abv2_value'])) / EIGHT_CHANNEL_PAPA[device_code]['pa2_value'])) *
                                                          EIGHT_CHANNEL_PAPA[device_code]['sp2_value'] / 100))
                            ch3_amp = int.from_bytes(data[num * 10 + 4:num * 10 + 6],
                                                     byteorder='big')
                            cal_ch3_amp = float('%.2f' % ((10 ** ((ch3_amp - (
                                    EIGHT_CHANNEL_PAPA[device_code]['bv3_value'] + EIGHT_CHANNEL_PAPA[device_code][
                                'abv3_value'])) / EIGHT_CHANNEL_PAPA[device_code]['pa3_value'])) *
                                                          EIGHT_CHANNEL_PAPA[device_code]['sp3_value'] / 100))
                            org_phase = int.from_bytes(data[num * 10 + 6:num * 10 + 10], byteorder='big')  # 原相位
                            cal_phase = (org_phase % 40000 / 40000) * 360  # 计算后相位
                            cal_cycle = math.floor(org_phase / 40000)  # 计算后周期(向下取整)

                            ch1_amplitudeArray.append(cal_ch1_amp)
                            ch2_amplitudeArray.append(cal_ch2_amp)
                            ch3_amplitudeArray.append(cal_ch3_amp)
                            phaseArray.append(cal_phase)
                            cycleArray.append(cal_cycle)

                    else:
                        logging.info('[%s]:atlas data is empty' % device_code)
            else:
                logging.info('[%s]:crc_flag is False' % device_code)

            data_res = {'channel_number': channel, 'amplitude': amplitude, 'frequency': frequency, 'energy': energy,
                        'alarm': alarm_value, 'ch1_amplitudeArray': ch1_amplitudeArray,
                        'ch2_amplitudeArray': ch2_amplitudeArray, 'ch3_amplitudeArray': ch3_amplitudeArray,
                        'phaseArray': phaseArray, 'cycleArray': cycleArray}
            pd_data.append(data_res)

        if temp_numb > 0:  # 读取温度数据
            crc_flag = True  # crc校验标志
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x03, 0x30, 0x00, temp_numb * 2)  # 读取温度数据
            logging.debug((device_code, "temp_cmd: " + ''.join(['%02X ' % b for b in byte_cmd])))
            cli_sk.send(byte_cmd)
            # sock.settimeout(5)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, "recv_data: " + ''.join(['%02X ' % b for b in recv_data])))
            else:
                crc_flag = False

            alarm_cmd = pf.modbus_command(slave_id, 0x01, 0x00, 0x09, 0x00, temp_numb)  # 读取报警状态
            cli_sk.send(alarm_cmd)
            alarm_data = pf.data_receive(cli_sk)
            if alarm_data:
                logging.debug((device_code, "alarm_data: " + ''.join(['%02X ' % b for b in alarm_data])))
            else:
                crc_flag = False

            if crc_flag:
                alarm_list = []
                num = math.ceil(temp_numb / 8)
                for i in range(num):
                    l1 = []
                    idx = 3 + i
                    bin_str = bin(int(alarm_data[idx]))[2:].zfill(8)
                    logging.debug(bin_str)
                    for j in bin_str:
                        if j == '1':
                            l1.append(1)
                        else:
                            l1.append(0)
                    l1.reverse()
                    alarm_list.extend(l1)
                    logging.debug(alarm_list)
                logging.debug((device_code, alarm_list))

                for channel in range(1, temp_numb + 1):
                    temp_value = int.from_bytes(recv_data[4 * channel - 1:4 * channel + 3], byteorder='big')
                    # if temp_value >= 32768:
                    #     temp_value -= 65536
                    if temp_value >= 2147483648:
                        temp_value -= 4294967296
                    temp_value = temp_value / 10

                    temp_res = {"channel": channel, "temp": temp_value, "alarm": alarm_list[channel - 1]}
                    temp_data.append(temp_res)
                logging.debug((device_code, temp_data))
            else:
                logging.info('[%s]:crc_flag is False' % device_code)

        data_1 = {'01_pdData': pd_data, '01_tempData': temp_data}
        data_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(data_1)}
        data_dict = {'data_type': 'data', 'data': json.dumps(data_2),
                     'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        data_json = json.dumps(data_dict)
        logging.debug((device_code, data_json))
        redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
        logging.info('[%s]:redis set data success' % device_code)
    else:
        logging.error('[%s]:redis set data fail' % device_code)


def three_channel_collect(redis_conn, cli_sk, device_code, slave_id, device_type, dev_para_list):
    """
    三通道采集程序-02
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        dev_para_list: 已读取过参数的设备

    Returns: None

    """
    # 三通道参数默认值
    pa1_value = 470  # db系数
    pa2_value = 470
    pa3_value = 470
    bv1_value = 500  # 基值
    bv2_value = 500
    bv3_value = 500
    abv1_value = 0  # 附加基值
    abv2_value = 0
    abv3_value = 0
    sp1_value = 100  # 传感系数
    sp2_value = 100
    sp3_value = 100

    crc_flag = True
    if device_code not in dev_para_list:  # 该设备未读取过参数
        para_list = []  # [{'address': '0001', 'value': 5}, {'address': '0002', 'value': 625}, ...]
        for n in range(3):
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x01, 0x00, 0x60)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, recv_data))
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                for i in range(0, 96):
                    address = '%04X' % (i + 1)
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    if address in {'0024', '0025', '002E', '004C'}:
                        if value >= 32768:  # 0-65535转有符号-32768至32768
                            value -= 65536
                    para_list.append({'address': address, 'value': value})

                    if address == '0007':
                        pa1_value = value
                    elif address == '000C':
                        pa2_value = value
                    elif address == '0029':
                        pa3_value = value
                    elif address == '0006':
                        bv1_value = value
                    elif address == '000B':
                        bv2_value = value
                    elif address == '0028':
                        bv3_value = value
                    elif address == '0024':
                        abv1_value = value
                    elif address == '0025':
                        abv2_value = value
                    elif address == '002E':
                        abv3_value = value
                    elif address == '000A':
                        sp1_value = value
                    elif address == '000F':
                        sp2_value = value
                    elif address == '002C':
                        sp3_value = value

                THREE_CHANNEL_PAPA[device_code] = {'pa1_value': pa1_value, 'pa2_value': pa2_value,
                                                   'pa3_value': pa3_value,
                                                   'bv1_value': bv1_value, 'bv2_value': bv2_value,
                                                   'bv3_value': bv3_value,
                                                   'abv1_value': abv1_value, 'abv2_value': abv2_value,
                                                   'abv3_value': abv3_value,
                                                   'sp1_value': sp1_value, 'sp2_value': sp2_value,
                                                   'sp3_value': sp3_value}
                break
            else:
                if n == 2:
                    crc_flag = False

        logging.debug((device_code, para_list))
        logging.debug((device_code, pa1_value, pa2_value, pa3_value,
                       bv1_value, bv2_value, bv3_value,
                       abv1_value, abv2_value, abv3_value,
                       sp1_value, sp2_value, sp3_value))

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x05, 0x00, 0x00, 0x02)  # 读取设备编码
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                dev_ins_id = int.from_bytes(recv_data[3:7], byteorder='big')
            else:
                dev_ins_id = ''

            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x21, 0x00, 0x01)  # 读取波特率
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                data = int.from_bytes(recv_data[3:5], byteorder='big')
                if data == 85:  # 0x55
                    baudrate = 9600
                elif data == 170:  # 0xAA
                    baudrate = 115200
                else:
                    baudrate = ''
            else:
                baudrate = ''

            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x05, 0x10, 0x00, 0x01)  # 读取程序版本号
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                soft_version = str(binascii.hexlify(recv_data[3:5]), encoding='utf-8')
            else:
                soft_version = ''

            dev_info = {'device_inside_id': dev_ins_id, 'baudrate': baudrate, 'software_version': soft_version,
                        'hardware_version': '', 'lf': 'ch3', 'mf': 'ch1', 'hf': 'ch2'}
            logging.debug((device_code, dev_info))

            para_1 = {'device_info': dev_info, 'para_dictionary_table': para_list}
            para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
            para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            para_json = json.dumps(para_dict)
            logging.debug((device_code,
                           para_json))  # {"data_type": "parameter", "data": "{\"device_type\": \"01\", \"device_code\": \"gz0124010001\", \"data\": \"{\\\"device_info\\\": {\\\"device_inside_id\\\": 202811, \\\"baudrate\\\": 115200, \\\"software_version\\\": \\\"2366\\\", \\\"hardware_version\\\": \\\"\\\", \\\"lf\\\": \\\"ch3\\\", \\\"mf\\\": \\\"ch1\\\", \\\"hf\\\": \\\"ch2\\\"}, \\\"para_dictionary_table\\\": [{\\\"address\\\": \\\"0001\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0002\\\", \\\"value\\\": 625}, {\\\"address\\\": \\\"0003\\\", \\\"value\\\": 3}, {\\\"address\\\": \\\"0004\\\", \\\"value\\\": 8}, {\\\"address\\\": \\\"0005\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0006\\\", \\\"value\\\": 363}, {\\\"address\\\": \\\"0007\\\", \\\"value\\\": 450}, {\\\"address\\\": \\\"0008\\\", \\\"value\\\": 20}, {\\\"address\\\": \\\"0009\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"000A\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"000B\\\", \\\"value\\\": 325}, {\\\"address\\\": \\\"000C\\\", \\\"value\\\": 508}, {\\\"address\\\": \\\"000D\\\", \\\"value\\\": 20}, {\\\"address\\\": \\\"000E\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"000F\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"0010\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"0011\\\", \\\"value\\\": 10}, {\\\"address\\\": \\\"0012\\\", \\\"value\\\": 500}, {\\\"address\\\": \\\"0013\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"0014\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"0015\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"0016\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0017\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0018\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0019\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001A\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001B\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001C\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001D\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001E\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"001F\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"0020\\\", \\\"value\\\": 5000}, {\\\"address\\\": \\\"0021\\\", \\\"value\\\": 170}, {\\\"address\\\": \\\"0022\\\", \\\"value\\\": 900}, {\\\"address\\\": \\\"0023\\\", \\\"value\\\": 650}, {\\\"address\\\": \\\"0024\\\", \\\"value\\\": 190}, {\\\"address\\\": \\\"0025\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0026\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0027\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0028\\\", \\\"value\\\": 433}, {\\\"address\\\": \\\"0029\\\", \\\"value\\\": 508}, {\\\"address\\\": \\\"002A\\\", \\\"value\\\": 20}, {\\\"address\\\": \\\"002B\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"002C\\\", \\\"value\\\": 100}, {\\\"address\\\": \\\"002D\\\", \\\"value\\\": 50}, {\\\"address\\\": \\\"002E\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"002F\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0030\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0031\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0032\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0033\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0034\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0035\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0036\\\", \\\"value\\\": 117}, {\\\"address\\\": \\\"0037\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"0038\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"0039\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003A\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003B\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003C\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003D\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003E\\\", \\\"value\\\": 1301}, {\\\"address\\\": \\\"003F\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0040\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0041\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0042\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0043\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0044\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0045\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0046\\\", \\\"value\\\": 64450}, {\\\"address\\\": \\\"0047\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"0048\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"0049\\\", \\\"value\\\": 160}, {\\\"address\\\": \\\"004A\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"004B\\\", \\\"value\\\": 43690}, {\\\"address\\\": \\\"004C\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"004D\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"004E\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"004F\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0050\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0051\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0052\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0053\\\", \\\"value\\\": 10}, {\\\"address\\\": \\\"0054\\\", \\\"value\\\": 10}, {\\\"address\\\": \\\"0055\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0056\\\", \\\"value\\\": 85}, {\\\"address\\\": \\\"0057\\\", \\\"value\\\": 1}, {\\\"address\\\": \\\"0058\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"0059\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"005A\\\", \\\"value\\\": 0}, {\\\"address\\\": \\\"005B\\\", \\\"value\\\": 30}, {\\\"address\\\": \\\"005C\\\", \\\"value\\\": 3}, {\\\"address\\\": \\\"005D\\\", \\\"value\\\": 30}, {\\\"address\\\": \\\"005E\\\", \\\"value\\\": 3}, {\\\"address\\\": \\\"005F\\\", \\\"value\\\": 30}, {\\\"address\\\": \\\"0060\\\", \\\"value\\\": 3}]}\"}", "update_time": "2024-05-20 18:05:46"}
            redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
            logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

    logging.debug(THREE_CHANNEL_PAPA)
    logging.debug((device_code, crc_flag))
    if crc_flag and device_code in THREE_CHANNEL_PAPA:
        pd_data = []  # 局放数据
        for channel in range(1, 4):  # 读取三通道数据
            crc_flag = True  # crc校验标志
            amplitude = 0
            frequency = 0
            energy = 0
            alarm_value = 0
            ch1_amplitudeArray = []
            ch2_amplitudeArray = []
            ch3_amplitudeArray = []
            phaseArray = []
            cycleArray = []

            address_l = (channel - 1) * 6
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x01, address_l, 0x00, 0x06)  # 读取幅值、频次等数据
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, "recv_data: " + ''.join(['%02X ' % b for b in recv_data])))
                amplitude = int.from_bytes(recv_data[3:5], byteorder='big')  # 幅值
                frequency = int.from_bytes(recv_data[5:7], byteorder='big')  # 频次
                energy = int.from_bytes(recv_data[7:11], byteorder='big')  # 能量
                alarm_value = int.from_bytes(recv_data[11:13], byteorder='big')  # 报警
            else:
                crc_flag = False

            if crc_flag:
                if frequency > 0:  # 读取谱图
                    address_l = channel + 1
                    atlas_cmd = pf.modbus_command(slave_id, 0x05, 0x02, address_l, 0xFF, 0x00)
                    logging.debug(
                        (device_code, 'dev_id:' + str(slave_id), 'channel:' + str(channel),
                         'dev_type:' + device_type,
                         "atlas_cmd: " + ''.join(['%02X ' % b for b in atlas_cmd])))
                    cli_sk.send(atlas_cmd)
                    atlas_data = pf.data_receive(cli_sk)
                    logging.debug((device_code, 'dev_id:' + str(slave_id), 'channel:' + str(channel),
                                   "atlas_data: " + ''.join(
                                       ['%02X ' % b for b in atlas_data])))
                    if atlas_data:
                        data_len = int.from_bytes(atlas_data[5:7],
                                                  byteorder='big')  # 数据长度
                        logging.debug((device_code, 'dev_id:' + str(slave_id),
                                       'channel:' + str(channel), data_len))
                        group_len = (data_len - 9) // 10  # 共多少组数据
                        data = atlas_data[7:data_len - 2]  # 谱图数据
                        logging.debug(
                            (device_code, 'dev_id:' + str(slave_id), 'channel:' + str(channel),
                             "data recv:" + ''.join(['%02X ' % b for b in data])))
                        for num in range(group_len):
                            ch1_amp = int.from_bytes(data[num * 10 + 0:num * 10 + 2],
                                                     byteorder='big')  # 原幅值
                            cal_ch1_amp = float('%.2f' % ((10 ** ((ch1_amp - (
                                    THREE_CHANNEL_PAPA[device_code]['bv1_value'] + THREE_CHANNEL_PAPA[device_code][
                                'abv1_value'])) / THREE_CHANNEL_PAPA[device_code]['pa1_value'])) *
                                                          THREE_CHANNEL_PAPA[device_code][
                                                              'sp1_value'] / 100))  # 计算后幅值(Pc)
                            ch2_amp = int.from_bytes(data[num * 10 + 2:num * 10 + 4],
                                                     byteorder='big')
                            cal_ch2_amp = float('%.2f' % ((10 ** ((ch2_amp - (
                                    THREE_CHANNEL_PAPA[device_code]['bv2_value'] + THREE_CHANNEL_PAPA[device_code][
                                'abv2_value'])) / THREE_CHANNEL_PAPA[device_code]['pa2_value'])) *
                                                          THREE_CHANNEL_PAPA[device_code]['sp2_value'] / 100))
                            ch3_amp = int.from_bytes(data[num * 10 + 4:num * 10 + 6],
                                                     byteorder='big')
                            cal_ch3_amp = float('%.2f' % ((10 ** ((ch3_amp - (
                                    THREE_CHANNEL_PAPA[device_code]['bv3_value'] + THREE_CHANNEL_PAPA[device_code][
                                'abv3_value'])) / THREE_CHANNEL_PAPA[device_code]['pa3_value'])) *
                                                          THREE_CHANNEL_PAPA[device_code]['sp3_value'] / 100))
                            org_phase = int.from_bytes(data[num * 10 + 6:num * 10 + 10], byteorder='big')  # 原相位
                            cal_phase = (org_phase % 40000 / 40000) * 360  # 计算后相位
                            cal_cycle = math.floor(org_phase / 40000)  # 计算后周期(向下取整)

                            ch1_amplitudeArray.append(cal_ch1_amp)
                            ch2_amplitudeArray.append(cal_ch2_amp)
                            ch3_amplitudeArray.append(cal_ch3_amp)
                            phaseArray.append(cal_phase)
                            cycleArray.append(cal_cycle)

                    else:
                        logging.info('[%s]:atlas data is empty' % device_code)
            else:
                logging.info('[%s]:crc_flag is False' % device_code)

            data_res = {'channel_number': channel, 'amplitude': amplitude, 'frequency': frequency, 'energy': energy,
                        'alarm': alarm_value, 'ch1_amplitudeArray': ch1_amplitudeArray,
                        'ch2_amplitudeArray': ch2_amplitudeArray, 'ch3_amplitudeArray': ch3_amplitudeArray,
                        'phaseArray': phaseArray, 'cycleArray': cycleArray}
            pd_data.append(data_res)

        data_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(pd_data)}
        data_dict = {'data_type': 'data', 'data': json.dumps(data_2),
                     'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        data_json = json.dumps(data_dict)
        logging.debug((device_code, data_json))
        redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
        logging.info('[%s]:redis set data success' % device_code)
    else:
        logging.error('[%s]:redis set data fail' % device_code)


def aa_tev_collect(redis_conn, cli_sk, device_code, slave_id, device_type, dev_para_list):
    """
    485超声地电二合一采集程序-04
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        dev_para_list: 已读取过参数的设备

    Returns: None

    """
    crc_flag = True
    if device_code not in dev_para_list:
        baudrate = 115200
        para_list = []
        for n in range(3):
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x00, 0x00, 0x41)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, recv_data))
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                for i in range(0, 65):
                    address = '%04X' % i
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    if address == '0001':
                        if value == 1:  # 0x01
                            baudrate = 1200
                        elif value == 2:  # 0x02
                            baudrate = 2400
                        elif value == 3:  # 0x03
                            baudrate = 4800
                        elif value == 4:  # 0x04
                            baudrate = 9600
                        elif value == 5:  # 0x05
                            baudrate = 19200
                        elif value == 6:  # 0x06
                            baudrate = 38400
                        elif value == 7:  # 0x07
                            baudrate = 57600
                        elif value == 8:  # 0x08
                            baudrate = 115200

                    if address in {'0012', '0013', '0014', '0015', '0022', '0023', '0024', '0025', '002E', '002F',
                                   '0030', '0031', '003A', '003B', '003C', '003D', '003E', '003F'}:
                        value = pf.int_to_int16(value)
                        if address in {'003E', '003F'}:
                            value /= 10
                    para_list.append({'address': address, 'value': value})
                break
            else:
                if n == 2:
                    crc_flag = False

        logging.debug((device_code, para_list))

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x45, 0x00, 0x07)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                software_version = str(binascii.hexlify(recv_data[3:5]), encoding='utf-8')  # 软件主版本号
                dev_type = str(binascii.hexlify(recv_data[5:7]), encoding='utf-8')  # 设备类型
                software_subversion = str(binascii.hexlify(recv_data[7:9]), encoding='utf-8')  # 软件子版本号
                lora_id = str(binascii.hexlify(recv_data[13:17]), encoding='utf-8')  # LORA ID
            else:
                software_version = ''
                dev_type = ''
                software_subversion = ''
                lora_id = ''

            dev_info = {'software_version': software_version, 'device_type': dev_type,
                        'software_subversion': software_subversion, 'lora_id': lora_id, 'baudrate': baudrate}
            logging.debug((device_code, dev_info))
            para_1 = {'device_info': dev_info,
                      'para_dictionary_table': para_list}  # 'device_info': {'softwareMajorVersion': '1101', 'deviceType': '0041', 'softwareSubVersion': '1007', 'loraID': '00000000', 'baudrate': 115200}
            para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
            para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            para_json = json.dumps(para_dict)
            logging.debug((device_code, para_json))
            redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
            logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

    byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x50, 0x00, 0x14)  # 读取数据
    cli_sk.send(byte_cmd)
    recv_data = pf.data_receive(cli_sk)
    logging.debug((device_code, recv_data))
    if recv_data:
        logging.debug((device_code, ''.join(['%02X ' % i for i in
                                             recv_data])))  # 01 03 28 FC 18 FC 18 FC 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 7C 04 6A 04 6A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 88
        aa_peak_amp = int.from_bytes(recv_data[3:5], byteorder='big')
        aa_peak_amp = pf.int_to_int16(aa_peak_amp) / 100
        aa_mean_value = int.from_bytes(recv_data[5:7], byteorder='big')
        aa_mean_value = pf.int_to_int16(aa_mean_value) / 100
        aa_noise_mean = int.from_bytes(recv_data[7:9], byteorder='big')
        aa_noise_mean = pf.int_to_int16(aa_noise_mean) / 100
        aa_frequency = int.from_bytes(recv_data[9:11], byteorder='big')
        aa_pulse_cycle = int.from_bytes(recv_data[11:13], byteorder='big')
        aa_50Hz = int.from_bytes(recv_data[13:15], byteorder='big')
        aa_50Hz = pf.int_to_int16(aa_50Hz) / 100
        aa_100Hz = int.from_bytes(recv_data[15:17], byteorder='big')
        aa_100Hz = pf.int_to_int16(aa_100Hz) / 100
        aa_effective_value = int.from_bytes(recv_data[17:19], byteorder='big')
        aa_effective_value = pf.int_to_int16(aa_effective_value) / 100
        aa_noise_level = int.from_bytes(recv_data[19:21], byteorder='big')
        aa_noise_level = pf.int_to_int16(aa_noise_level) / 100
        aa_status = int.from_bytes(recv_data[21:23], byteorder='big')
        logging.debug((aa_peak_amp, aa_mean_value, aa_noise_mean, aa_frequency, aa_pulse_cycle, aa_50Hz, aa_100Hz,
                       aa_effective_value, aa_noise_level, aa_status))

        tev_peak_amp = int.from_bytes(recv_data[23:25], byteorder='big')
        tev_peak_amp = pf.int_to_int16(tev_peak_amp) / 100
        tev_mean_value = int.from_bytes(recv_data[25:27], byteorder='big')
        tev_mean_value = pf.int_to_int16(tev_mean_value) / 100
        tev_noise_mean = int.from_bytes(recv_data[27:29], byteorder='big')
        tev_noise_mean = pf.int_to_int16(tev_noise_mean) / 100
        tev_frequency = int.from_bytes(recv_data[29:31], byteorder='big')
        tev_pulse_cycle = int.from_bytes(recv_data[31:33], byteorder='big')
        tev_50Hz = int.from_bytes(recv_data[33:35], byteorder='big')
        tev_50Hz = pf.int_to_int16(tev_50Hz) / 100
        tev_100Hz = int.from_bytes(recv_data[35:37], byteorder='big')
        tev_100Hz = pf.int_to_int16(tev_100Hz) / 100
        tev_effective_value = int.from_bytes(recv_data[37:39], byteorder='big')
        tev_effective_value = pf.int_to_int16(tev_effective_value) / 100
        tev_noise_level = int.from_bytes(recv_data[39:41], byteorder='big')
        tev_noise_level = pf.int_to_int16(tev_noise_level) / 100
        tev_status = int.from_bytes(recv_data[41:43], byteorder='big')
        logging.debug((
            tev_peak_amp, tev_mean_value, tev_noise_mean, tev_frequency, tev_pulse_cycle, tev_50Hz, tev_100Hz,
            tev_effective_value, tev_noise_level, tev_status))

        byte_cmd = pf.modbus_command(slave_id, 0x01, 0x00, 0xA1, 0x00, 0x02)  # 读取报警
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        logging.debug((device_code, recv_data))
        if recv_data:
            logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
            bin_str = bin(int(recv_data[3]))[2:].zfill(8)
            aa_alarm = int(bin_str[-1])
            tev_alarm = int(bin_str[-2])
        else:
            aa_alarm = 0
            tev_alarm = 0

        byte_cmd = pf.modbus_command(slave_id, 0x01, 0x00, 0xB1, 0x00, 0x02)  # 读取预警
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        logging.debug((device_code, recv_data))
        if recv_data:
            logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
            bin_str = bin(int(recv_data[3]))[2:].zfill(8)
            aa_forewarning = int(bin_str[-1])
            tev_forewarning = int(bin_str[-2])
        else:
            aa_forewarning = 0
            tev_forewarning = 0

        aa_amp_list = []
        aa_phase_list = []
        aa_cycle_list = []
        tev_amp_list = []
        tev_phase_list = []
        tev_cycle_list = []
        if aa_frequency > 0:
            aa_atlas_data = pf.atlas_read_04(cli_sk, slave_id, aa_frequency, 0x00,
                                             0x01)  # 0DDE 01D5 0E10 03C9...(幅值 相位 幅值 相位...)
            logging.debug(aa_atlas_data)
            logging.debug(''.join(['%02X ' % i for i in aa_atlas_data]))
            for i in range(len(aa_atlas_data) // 4):
                org_amp = aa_atlas_data[i * 4:i * 4 + 2]
                org_amp = int.from_bytes(org_amp, byteorder='big')
                cal_amp = pf.int_to_int16(org_amp) / 100  # 计算后幅值
                # cal_amp = pf.int_to_int16(org_amp)  # 计算后幅值

                org_phase = aa_atlas_data[i * 4 + 2:i * 4 + 4]
                org_phase = int.from_bytes(org_phase, byteorder='big')  # 原相位
                logging.debug((cal_amp, org_phase))
                cal_phase = (org_phase % 1000 / 1000) * 360  # 计算后相位
                cal_cycle = math.floor(org_phase / 1000)  # 计算后周期(向下取整)

                aa_amp_list.append(cal_amp)
                aa_phase_list.append(cal_phase)
                aa_cycle_list.append(cal_cycle)
        if tev_frequency > 0:
            tev_atlas_data = pf.atlas_read_04(cli_sk, slave_id, tev_frequency, 0x00,
                                              0x02)  # 0DDE 01D5 0E10 03C9...(幅值 相位 幅值 相位...)
            logging.debug(tev_atlas_data)
            logging.debug(''.join(['%02X ' % i for i in tev_atlas_data]))
            for i in range(len(tev_atlas_data) // 4):
                org_amp = tev_atlas_data[i * 4:i * 4 + 2]
                org_amp = int.from_bytes(org_amp, byteorder='big')
                # cal_amp = pf.int_to_int16(org_amp) / 100  # 计算后幅值
                cal_amp = pf.int_to_int16(org_amp)  # 计算后幅值 todo

                org_phase = tev_atlas_data[i * 4 + 2:i * 4 + 4]
                org_phase = int.from_bytes(org_phase, byteorder='big')  # 原相位
                logging.debug((cal_amp, org_phase))
                cal_phase = (org_phase % 1000 / 1000) * 360  # 计算后相位
                cal_cycle = math.floor(org_phase / 1000)  # 计算后周期(向下取整)

                tev_amp_list.append(cal_amp)
                tev_phase_list.append(cal_phase)
                tev_cycle_list.append(cal_cycle)

        data_1 = {
            "04_data": {"aa": {"aa_map": {"aa_amp": aa_amp_list, "aa_phase": aa_phase_list, "aa_cycle": aa_cycle_list},
                               "aa_data": {"aa_peak_amp": aa_peak_amp, "aa_mean_value": aa_mean_value,
                                           "aa_noise_mean": aa_noise_mean,
                                           "aa_frequency": aa_frequency, "aa_pulse_cycle": aa_pulse_cycle,
                                           "aa_50Hz": aa_50Hz, "aa_100Hz": aa_100Hz,
                                           "aa_alarm": aa_alarm, "aa_forewarning": aa_forewarning,
                                           "aa_effective_value": aa_effective_value,
                                           "aa_noise_level": aa_noise_level, "aa_status": aa_status}},
                        "tev": {"tev_map": {"tev_amp": tev_amp_list, "tev_phase": tev_phase_list,
                                            "tev_cycle": tev_cycle_list},
                                "tev_data": {"tev_peak_amp": tev_peak_amp, "tev_mean_value": tev_mean_value,
                                             "tev_noise_mean": tev_noise_mean,
                                             "tev_frequency": tev_frequency, "tev_pulse_cycle": tev_pulse_cycle,
                                             "tev_50Hz": tev_50Hz, "tev_100Hz": tev_100Hz,
                                             "tev_alarm": tev_alarm, "tev_forewarning": tev_forewarning,
                                             "tev_effective_value": tev_effective_value,
                                             "tev_noise_level": tev_noise_level, "tev_status": tev_status}}}}

        data_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(data_1)}
        data_dict = {'data_type': 'data', 'data': json.dumps(data_2),
                     'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        data_json = json.dumps(data_dict)
        logging.debug((device_code, data_json))
        redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
        logging.info('[%s]:redis set data success' % device_code)
    else:
        logging.error('[%s]:redis set data fail' % device_code)


def wireless_temperature_collect(redis_conn, cli_sk, device_code, slave_id, device_type, temp_numb, dev_para_list):
    """
    无线测温采集程序-10
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        temp_numb: 温度传感器数量(int)
        dev_para_list: 已读取过参数的设备

    Returns: None

    """
    if device_code not in dev_para_list:  # 该设备未读取过参数
        para_list = [{'address': '0176', 'value': 115200}]
        params = []
        byte_cmd = pf.modbus_command(slave_id, 0x03, 0x01, 0x77, 0x00, 0x07)  # 读取参数
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        logging.debug((device_code, recv_data))
        if recv_data:
            logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
            start_address = 0x0177
            for i, byte in enumerate(recv_data):
                if i < 3 or i >= 17:
                    continue
                if i % 2 == 1:
                    address = f"{start_address:04X}"
                    hex_value = '%02X' % byte + '%02X' % recv_data[i + 1]
                    para_list.append({'address': address,
                                      'value': int(hex_value, 16)})
                    params.append(int(hex_value, 16))
                    start_address += 1
            logging.debug((device_code, para_list))

            wireless_temp_params = ['485id', 'high_temp_alarm_threshold', 'abnormal_temp_display',
                                    'high_temp_warning_threshold', 'software_version', 'wirelss_address',
                                    'host_temp_number', 'device_inside_id', 'baudrate']
            dev_info = dict(zip(wireless_temp_params, params))
            dev_info['device_inside_id'] = dev_info['host_temp_number']
            dev_info['baudrate'] = 115200
            logging.debug((device_code, dev_info))

            para_1 = {'device_info': dev_info, 'para_dictionary_table': para_list}
            para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
            para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            para_json = json.dumps(para_dict)
            logging.debug((device_code, para_json))
            redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
            logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

    if temp_numb > 0:  # 读取温度数据
        crc_flag = True  # crc校验标志
        temp_data = []
        byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x00, 0x00, temp_numb)  # 读取温度数据
        logging.debug((device_code, "temp_cmd: " + ''.join(['%02X ' % b for b in byte_cmd])))
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        if recv_data:
            logging.debug((device_code, "recv_data: " + ''.join(['%02X ' % b for b in recv_data])))
        else:
            crc_flag = False

        alarm_cmd = pf.modbus_command(slave_id, 0x01, 0x01, 0x7F, 0x00, temp_numb)  # 读取报警状态
        cli_sk.send(alarm_cmd)
        alarm_data = pf.data_receive(cli_sk)
        if alarm_data:
            logging.debug((device_code, "alarm_data: " + ''.join(['%02X ' % b for b in alarm_data])))
        else:
            crc_flag = False

        if crc_flag:
            alarm_list = []
            num = math.ceil(temp_numb / 8)
            for i in range(num):
                l1 = []
                idx = 3 + i
                bin_str = bin(int(alarm_data[idx]))[2:].zfill(8)
                logging.debug(bin_str)
                for j in bin_str:
                    if j == '1':
                        l1.append(1)
                    else:
                        l1.append(0)
                l1.reverse()
                alarm_list.extend(l1)
                logging.debug(alarm_list)
            logging.debug((device_code, alarm_list))

            for channel in range(1, temp_numb + 1):
                temp_value = int.from_bytes(recv_data[channel * 2 + 1:channel * 2 + 3], byteorder='big')
                temp_value = (pf.int_to_int16(temp_value)) / 10

                temp_res = {"channel_number": channel, "temp": temp_value, "alarm": alarm_list[channel - 1]}
                temp_data.append(temp_res)
            logging.debug((device_code, temp_data))

            data_1 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(temp_data)}
            data_dict = {'data_type': 'data', 'data': json.dumps(data_1),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            data_json = json.dumps(data_dict)
            logging.debug((device_code, data_json))
            redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
            logging.info('[%s]:redis set data success' % device_code)
        else:
            logging.error('[%s]:redis set data fail' % device_code)


def circulation_collect(redis_conn, cli_sk, device_code, slave_id, device_type, dev_para_list):
    """
    环流采集程序-12
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        dev_para_list: 已读取过参数的设备

    Returns: None

    """
    crc_flag = True
    if device_code not in dev_para_list:  # 该设备未读取过参数
        para_list = []
        for n in range(3):
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x0B, 0x00, 0x01)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, recv_data))
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                decimal_method = int.from_bytes(recv_data[3:5], byteorder='big')
                CIRCU_DECIMAL_PARA[device_code] = decimal_method
                break
            else:
                if n == 2:
                    crc_flag = False

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x00, 0x00, 0x0C)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, recv_data))
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                software_version = str(binascii.hexlify(recv_data[3:5]), encoding='utf-8')
                hardware_version = str(binascii.hexlify(recv_data[5:7]), encoding='utf-8')
                device_inside_id = int.from_bytes(recv_data[7:9], byteorder='big')
                baudrate = int.from_bytes(recv_data[9:11], byteorder='big')
                if baudrate == 1:
                    baudrate = 9600
                elif baudrate == 2:
                    baudrate = 115200
                for i in range(4, 12):
                    address = '%04X' % i
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    para_list.append({'address': address, 'value': value})
                logging.debug(para_list)

                dev_info = {'device_inside_id': device_inside_id, 'baudrate': baudrate,
                            'software_version': software_version, 'hardware_version': hardware_version}
                logging.debug((device_code, dev_info))
                para_1 = {'device_info': dev_info, 'para_dictionary_table': para_list}
                para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
                para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                             'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
                para_json = json.dumps(para_dict)
                logging.debug((device_code, para_json))
                redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
                logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

    if crc_flag and device_code in CIRCU_DECIMAL_PARA:
        byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x23, 0x00, 0x0C)  # 读取数据
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        logging.debug((device_code, recv_data))
        if recv_data:
            logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
            ch1_value = int.from_bytes(recv_data[3:7], byteorder='big')
            ch2_value = int.from_bytes(recv_data[7:11], byteorder='big')
            ch3_value = int.from_bytes(recv_data[11:15], byteorder='big')
            ch4_value = int.from_bytes(recv_data[15:19], byteorder='big')
            ch1_alarm = int.from_bytes(recv_data[19:21], byteorder='big')
            ch2_alarm = int.from_bytes(recv_data[21:23], byteorder='big')
            ch3_alarm = int.from_bytes(recv_data[23:25], byteorder='big')
            ch4_alarm = int.from_bytes(recv_data[25:27], byteorder='big')
            if CIRCU_DECIMAL_PARA[device_code] == 0:
                ch1_value /= 100
                ch2_value /= 100
                ch3_value /= 100
                ch4_value /= 100
            elif CIRCU_DECIMAL_PARA[device_code] == 1:
                ch1_value /= 10
                ch2_value /= 10
                ch3_value /= 10
                ch4_value /= 10
            elif CIRCU_DECIMAL_PARA[device_code] == 2:
                ch1_value = round(ch1_value / 10)
                ch2_value = round(ch2_value / 10)
                ch3_value = round(ch3_value / 10)
                ch4_value = round(ch4_value / 10)

            cc_data = [{'channel_number': 1, 'cc': ch1_value, 'alarm': ch1_alarm},
                       {'channel_number': 2, 'cc': ch2_value, 'alarm': ch2_alarm},
                       {'channel_number': 3, 'cc': ch3_value, 'alarm': ch3_alarm},
                       {'channel_number': 4, 'cc': ch4_value, 'alarm': ch4_alarm}]
            data_1 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(cc_data)}
            data_dict = {'data_type': 'data', 'data': json.dumps(data_1),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            data_json = json.dumps(data_dict)
            logging.debug((device_code, data_json))
            redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
            logging.info('[%s]:redis set data success' % device_code)
        else:
            logging.error('[%s]:redis set data fail' % device_code)


def voltage_tev_temp_water_collect(redis_conn, cli_sk, device_code, slave_id, device_type):
    """
    南网voltage+tev+temp+water采集程序-27  # todo 有需求再完善
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)

    Returns: None

    """
    if device_code not in DEV27_CONNECT_INFO:  # 首次连接
        DEV27_CONNECT_INFO[device_code] = {'first_time': time.time(), 'count': 1}
    else:
        DEV27_CONNECT_INFO[device_code]['count'] += 1
    logging.debug(DEV27_CONNECT_INFO)
    sleep_flag = False  # 休眠标志
    if DEV27_CONNECT_INFO[device_code]['count'] == 4:
        if (time.time() - DEV27_CONNECT_INFO[device_code]['first_time']) <= 300:
            sleep_flag = True
        del DEV27_CONNECT_INFO[device_code]

    if not sleep_flag:
        crc_flag = True  # crc校验标志
        para_list = []
        for n in range(3):
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x16, 0x00, 0x07)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                for i in range(0, 7):
                    address = '%04X' % (i + 22)
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    if address in {'0016', '0017', '0018', '0019'}:
                        if value >= 32768:
                            value -= 65536
                    para_list.append({'address': address, 'value': value})
                break
            else:
                if n == 2:
                    crc_flag = False

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x4A, 0x00, 0x0B)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                for i in range(0, 11):
                    address = '%04X' % (i + 74)
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    if address in {'004B', '004C', '004F', '0053', '0054'}:
                        if value >= 32768:
                            value -= 65536
                    para_list.append({'address': address, 'value': value})

            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x01, 0x00, 0x07)  # 读取波特率等参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                baudrate_data = int.from_bytes(recv_data[3:5], byteorder='big')
                if baudrate_data == 1:  # 0x01
                    baudrate = 1200
                elif baudrate_data == 2:  # 0x02
                    baudrate = 2400
                elif baudrate_data == 3:  # 0x03
                    baudrate = 4800
                elif baudrate_data == 4:  # 0x04
                    baudrate = 9600
                elif baudrate_data == 5:  # 0x05
                    baudrate = 19200
                elif baudrate_data == 6:  # 0x06
                    baudrate = 38400
                elif baudrate_data == 7:  # 0x07
                    baudrate = 57600
                elif baudrate_data == 8:  # 0x08
                    baudrate = 115200
                else:
                    baudrate = 0

                device_inside_id = int.from_bytes(recv_data[5:9], byteorder='big')
                software_main_version = int.from_bytes(recv_data[13:15], byteorder='big')
                software_sub_version = int.from_bytes(recv_data[15:17], byteorder='big')
            else:
                baudrate = ''
                device_inside_id = ''
                software_main_version = ''
                software_sub_version = ''

            dev_info = {'device_inside_id': device_inside_id, 'baudrate': baudrate,
                        'software_main_version': software_main_version,
                        'software_sub_version': software_sub_version, 'hardware_version': ''}
            logging.debug((device_code, dev_info))

            para_1 = {'device_info': dev_info, 'para_dictionary_table': para_list}
            para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
            para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            para_json = json.dumps(para_dict)
            logging.debug((device_code, para_json))
            redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
            logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x06, 0x00, 0x15, 0xCC, 0x77)  # 保活
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))

            byte_cmd = pf.modbus_command(slave_id, 0x06, 0x00, 0xFF, 0x00, 0x01)  # 解锁
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))

            time_difference = datetime.datetime.now() - datetime.datetime(2001, 1, 1)
            seconds_since_2001 = int(time_difference.total_seconds())
            time_byte = seconds_since_2001.to_bytes(4, byteorder='big')
            logging.debug(''.join(['%02X ' % b for b in time_byte]))
            data_1_h = int(time_byte[0])
            data_1_l = int(time_byte[1])
            data_2_h = int(time_byte[2])
            data_2_l = int(time_byte[3])
            byte_cmd = pf.modbus_command_10(slave_id, 0x10, 0x00, 0x09, 0x00, 0x02, 0x04, data_1_h, data_1_l, data_2_h,
                                            data_2_l)  # 校时
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))

            data_count = 0
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x10, 0x00, 0x01)  # 读取已缓存数据条数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))
                data_count = int.from_bytes(recv_data[3:5], byteorder='big')
                logging.debug((device_code, data_count))

            if data_count:
                data_1 = []
                for n in range(data_count):
                    address_h = (n * 32) // 256 + 1
                    address_l = n * 32 % 256
                    byte_cmd = pf.modbus_command(slave_id, 0x03, address_h, address_l, 0x00, 0x14)  # 读取数据
                    cli_sk.send(byte_cmd)
                    recv_data = pf.data_receive(cli_sk)
                    logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))
                    if recv_data and len(recv_data) > 10:
                        time_stamp = int.from_bytes(recv_data[3:7], byteorder='big')
                        if time_stamp != 0:
                            start_date = datetime.datetime(2001, 1, 1)
                            data_time = (start_date + datetime.timedelta(seconds=time_stamp)).strftime(
                                '%Y-%m-%d %H:%M:%S')
                            voltage = (int.from_bytes(recv_data[7:9], byteorder='big')) / 1000
                            voltage_alarm = int.from_bytes(recv_data[9:11], byteorder='big')
                            peak_value = int.from_bytes(recv_data[11:13], byteorder='big')
                            if peak_value >= 32768:
                                peak_value -= 65536
                            peak_value = peak_value / 100
                            discharge_average = int.from_bytes(recv_data[13:15], byteorder='big')
                            if discharge_average >= 32768:
                                discharge_average -= 65536
                            discharge_average = discharge_average / 100
                            noise_level = int.from_bytes(recv_data[15:17], byteorder='big')
                            if noise_level >= 32768:
                                noise_level -= 65536
                            noise_level = noise_level / 100
                            pulse_per_cycle = int.from_bytes(recv_data[17:19], byteorder='big')
                            frequency = int.from_bytes(recv_data[19:21], byteorder='big')
                            hz_50 = int.from_bytes(recv_data[21:23], byteorder='big')
                            hz_100 = int.from_bytes(recv_data[23:25], byteorder='big')
                            pd_warning = int.from_bytes(recv_data[25:27], byteorder='big')
                            pd_alarm = int.from_bytes(recv_data[27:29], byteorder='big')
                            env_temp = int.from_bytes(recv_data[29:31], byteorder='big')
                            if env_temp >= 32768:
                                env_temp -= 65536
                            env_temp = env_temp / 10
                            cable_temp_diff_warning = int.from_bytes(recv_data[31:33], byteorder='big')
                            cable_temp_diff_alarm = int.from_bytes(recv_data[33:35], byteorder='big')
                            cable_temp = int.from_bytes(recv_data[35:37], byteorder='big')
                            if cable_temp >= 32768:
                                cable_temp -= 65536
                            cable_temp = cable_temp / 10
                            cable_temp_warning = int.from_bytes(recv_data[37:39], byteorder='big')
                            cable_temp_alarm = int.from_bytes(recv_data[39:41], byteorder='big')
                            water_status = int.from_bytes(recv_data[41:43], byteorder='big')

                            data = {'data_time': data_time,
                                    'voltage_data': {'voltage': voltage, 'alarm': voltage_alarm},
                                    'tev_data': {'peak_value': peak_value, 'discharge_average': discharge_average,
                                                 'noise_level': noise_level, 'pulse_per_cycle': pulse_per_cycle,
                                                 'frequency': frequency, '50_hz': hz_50, '100_hz': hz_100,
                                                 'warning': pd_warning, 'alarm': pd_alarm},
                                    'temp_data': {'env_temp': env_temp,
                                                  'cable_temp_diff_warning': cable_temp_diff_warning,
                                                  'cable_temp_diff_alarm': cable_temp_diff_alarm,
                                                  'cable_temp': cable_temp,
                                                  'cable_temp_warning': cable_temp_warning,
                                                  'cable_temp_alarm': cable_temp_alarm},
                                    'water_data': {'water_status': water_status}}
                            data_1.append(data)

                    byte_cmd = pf.modbus_command(slave_id, 0x06, 0x00, 0x15, 0xCC, 0x77)  # 保活
                    cli_sk.send(byte_cmd)
                    recv_data = pf.data_receive(cli_sk)
                    logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))

                data_1.reverse()
                data_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(data_1)}
                data_dict = {'data_type': 'data', 'data': json.dumps(data_2),
                             'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
                data_json = json.dumps(data_dict)
                logging.debug((device_code, data_json))
                redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
                logging.info('[%s]:redis set data success' % device_code)

                byte_cmd = pf.modbus_command(slave_id, 0x06, 0x00, 0xFF, 0x00, 0x01)  # 解锁
                cli_sk.send(byte_cmd)
                recv_data = pf.data_receive(cli_sk)
                logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))

                byte_cmd = pf.modbus_command(slave_id, 0x06, 0x00, 0x10, 0x00, 0x00)  # 清缓存
                cli_sk.send(byte_cmd)
                recv_data = pf.data_receive(cli_sk)
                logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))
        else:
            logging.error('[%s]:redis set data fail' % device_code)

    for n in range(3):
        byte_cmd = pf.modbus_command(slave_id, 0x06, 0x00, 0x14, 0xCC, 0x77)  # 休眠
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))
        if recv_data:
            logging.info('[%s]:sleep' % device_code)
            break


def ntc_temperature_collect(redis_conn, cli_sk, device_code, slave_id, device_type, temp_numb):
    """
    中盛测温采集程序-80
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        temp_numb: 温度传感器数量(int)

    Returns: None

    """
    byte_cmd = pf.modbus_command(slave_id, 0x04, 0x00, 0x00, 0x00, temp_numb)  # 读取温度
    cli_sk.send(byte_cmd)
    recv_data = pf.data_receive(cli_sk)
    if recv_data:
        logging.debug((device_code, ''.join(['%02X ' % b for b in recv_data])))
        temp_data = []
        for i in range(temp_numb):
            channel_temp = int.from_bytes(recv_data[2 * i + 3:2 * i + 5], byteorder='big')
            channel_temp = -99.9 if channel_temp == 65535 else pf.int_to_int16(channel_temp) / 10
            temp_data.append({'channel_number': i + 1, 'temp': channel_temp, 'alarm': 0})

        data_1 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(temp_data)}
        data_dict = {'data_type': 'data', 'data': json.dumps(data_1),
                     'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        data_json = json.dumps(data_dict)
        logging.debug((device_code, data_json))
        redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
        logging.info('[%s]:redis set data success' % device_code)
    else:
        logging.error('[%s]:redis set data fail' % device_code)


def aa_tev_uhf_collect(redis_conn, cli_sk, device_code, slave_id, device_type, dev_para_list):
    """
    429三合一合一采集程序-06
    Args:
        redis_conn: redis连接
        cli_sk: 客户端socket
        device_code: 自定义设备编号(str)
        slave_id: 485id(int)
        device_type: 设备类型码(str)
        dev_para_list: 已读取过参数的设备

    Returns: None

    """
    uhf_base = 366
    uhf_add_base = 0
    uhf_db = 540
    uhf_sensor = 100

    para_start_address, para_end_address = 0x51, 0x9C
    para_counts = para_end_address - para_start_address + 1
    metric_start_address, metric_end_address = 0x01, 0x2B
    metric_counts = metric_end_address - metric_start_address + 1
    crc_flag = True
    if device_code not in dev_para_list:
        para_list = []
        for n in range(3):
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, para_start_address, 0x00, para_counts)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            logging.debug((device_code, recv_data))
            if recv_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
                for i in range(0, para_counts + 1):
                    address = '%04X' % (i + para_start_address)
                    value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
                    if address == '0052':
                        if value == 1:  # 0x01
                            value = 9600
                        elif value == 2:  # 0x02
                            value = 19200
                        elif value == 3:  # 0x03
                            value = 115200
                        elif value == 4:  # 0x04
                            value = 460800
                        else:
                            value = 115200

                    if address in {'0055', '0075', '0080', '008A', }:
                        value = pf.int_to_int16(value)
                    para_list.append({'address': address, 'value': value})

                    if address == '007C':
                        uhf_base = value
                    elif address == '007D':
                        uhf_db = value
                    elif address == '007E':
                        uhf_sensor = value
                    elif address == '0080':
                        uhf_add_base = value

                    UHF_PAPA[device_code] = {'uhf_base': uhf_base, 'uhf_db': uhf_db, 'uhf_sensor': uhf_sensor,
                                             'uhf_add_base': uhf_add_base}
                break
            else:
                if n == 2:
                    crc_flag = False
        logging.debug((device_code, para_list))

        if crc_flag:
            byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, 0x31, 0x00, 0x05)  # 读取参数
            cli_sk.send(byte_cmd)
            recv_data = pf.data_receive(cli_sk)
            if recv_data:
                software_version = str(binascii.hexlify(recv_data[3:5]), encoding='utf-8')  # 软件主版本号
                tev_threshold = int.from_bytes(recv_data[7:9], byteorder='big')
                uhf_threshold = int.from_bytes(recv_data[9:11], byteorder='big')
                aa_threshold = int.from_bytes(recv_data[11:13], byteorder='big')
            else:
                software_version = ''
                tev_threshold = 0
                uhf_threshold = 0
                aa_threshold = 0

            # para_list.append({'address': '0031', 'value': software_version})
            # para_list.append({'address': '0033', 'value': tev_threshold})
            # para_list.append({'address': '0034', 'value': uhf_threshold})
            # para_list.append({'address': '0035', 'value': aa_threshold})
            # dev_info = {'hardwareVersion': software_version}
            # for item in para_list:
            #     if item['address'] in DeviceSix.PARAMETERS_MAP.keys():
            #         key = DeviceSix.PARAMETERS_MAP[item['address']]
            #         dev_info[key] = item['value']

            dev_info = {'softwareVersion': software_version, 'hardwareVersion': software_version,
                        'aaThreshold': aa_threshold, 'tevThreshold': tev_threshold, 'uhfThreshold': uhf_threshold}
            logging.debug((device_code, dev_info))
            para_1 = {'device_info': dev_info,
                      'para_dictionary_table': para_list}  # 'device_info': {'softwareMajorVersion': '1101', 'deviceType': '0041', 'softwareSubVersion': '1007', 'loraID': '00000000', 'baudrate': 115200}
            para_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(para_1)}
            para_dict = {'data_type': 'parameter', 'data': json.dumps(para_2),
                         'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
            para_json = json.dumps(para_dict)
            logging.debug((device_code, para_json))
            redis_conn.rpush(pf.REDIS_CACHE_KEY, para_json)  # redis插入parameter数据
            logging.info('[%s]:redis set parameter success' % device_code)
        else:
            logging.error('[%s]:redis set parameter fail' % device_code)

    byte_cmd = pf.modbus_command(slave_id, 0x03, 0x00, metric_start_address, 0x00, metric_counts)  # 读取数据
    cli_sk.send(byte_cmd)
    recv_data = pf.data_receive(cli_sk)

    logging.debug((device_code, recv_data))
    aa_data = {}
    tev_data = {}
    uhf_data = {}
    if recv_data:
        logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
        for i in range(0, metric_counts + 1):
            address = '%04X' % (i+metric_start_address)
            value = int.from_bytes(recv_data[i * 2 + 3:i * 2 + 5], byteorder='big')
            if address in ['0001', '0003', '0004', '0X10', '0X12', '0X13', '0X15', '0X16']:
                value = pf.int_to_int16(value) / 10
            elif address in ['0007', '0008', '000A', '0017', '0018', '001A', '0020',
                             '0022', '0023', '0024', '0025', '0026', '0028', '0029', '002B']:
                value = value / 100
            if i+metric_start_address <= 0X0A:
                tev_key = DeviceSix.METRICS_MAP.get('tev').get(address)
                if tev_key:
                    tev_data[tev_key] = value
            elif 0x10 <= i+metric_start_address <= 0X1A:
                uhf_key = DeviceSix.METRICS_MAP.get('uhf').get(address)
                if uhf_key:
                    uhf_data[uhf_key] = value
            elif 0x20 <= i+metric_start_address <= 0X2B:
                aa_key = DeviceSix.METRICS_MAP.get('aa').get(address)
                if aa_key:
                    aa_data[aa_key] = value
        logging.info((tev_data, uhf_data, aa_data))
        tev_cycle_list = []
        tev_phase_list = []
        tev_amp_list = []
        tev_org_phase_list = []
        tev_freq = tev_data.get('frequency_tev_ch1')
        if tev_freq > 0:
            byte_cmd = pf.modbus_command(slave_id, 0x05, 0x01, 0x01, 0xFF, 0x00)  # 读取TEV谱图
            cli_sk.send(byte_cmd)
            tevatl_data = pf.data_receive(cli_sk)
            logging.debug((device_code, tevatl_data))
            if tevatl_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in tevatl_data])))
                data_len = int.from_bytes(tevatl_data[5:7], byteorder='big')  # 数据长度
                group_len = (data_len - 9) // 6  # 共多少组数据
                data = tevatl_data[7:data_len - 2]  # 谱图数据
                logging.debug("data recv:" + ''.join(['%02X ' % b for b in data]))
                for i in range(group_len):
                    org_amp = int.from_bytes(data[i * 6 + 0:i * 6 + 2], byteorder='big')  # 原幅值
                    cal_amp = pf.int_to_int16(org_amp) / 10  # todo
                    org_phase = int.from_bytes(data[i * 6 + 2:i * 6 + 6], byteorder='big')  # 原相位
                    cal_phase = (org_phase % 40000 / 40000) * 360  # 计算后相位
                    cal_cycle = math.floor(org_phase / 40000)  # 周期向下取整

                    tev_cycle_list.append(cal_cycle)
                    tev_phase_list.append(cal_phase)
                    tev_amp_list.append(cal_amp)
                    # tev_org_phase_list.append(org_phase)

        uhf_cycle_list = []
        uhf_phase_list = []
        uhf_amp_list = []
        uhf_org_phase_list = []
        uhf_freq = uhf_data.get('frequency_uhf_ch1')
        if uhf_freq > 0 and device_code in UHF_PAPA:
            byte_cmd = pf.modbus_command(slave_id, 0x05, 0x01, 0x02, 0xFF, 0x00)  # 读取UHF谱图
            cli_sk.send(byte_cmd)
            uhfatl_data = pf.data_receive(cli_sk)
            logging.debug((device_code, uhfatl_data))
            if uhfatl_data:
                logging.debug((device_code, ''.join(['%02X ' % i for i in uhfatl_data])))
                data_len = int.from_bytes(uhfatl_data[5:7], byteorder='big')  # 数据长度
                group_len = (data_len - 9) // 6  # 共多少组数据
                data = uhfatl_data[7:data_len - 2]  # 谱图数据
                logging.debug("data recv:" + ''.join(['%02X ' % b for b in data]))
                for i in range(group_len):
                    org_amp = int.from_bytes(data[i * 6 + 0:i * 6 + 2], byteorder='big')  # 原幅值
                    cal_amp = float('%.1f' % ((10 ** (
                            (org_amp - (UHF_PAPA[device_code]['uhf_base'] + UHF_PAPA[device_code]['uhf_add_base'])) /
                            UHF_PAPA[device_code]['uhf_db'])) * UHF_PAPA[device_code]['uhf_sensor'] / 100))  # 计算后幅值(Pc)
                    # if cal_amp > 0:
                    #     cal_amp = float('%.1f' % (math.log10(cal_amp / 10) * 20))  # todo 计算后幅值(dB)

                    org_phase = int.from_bytes(data[i * 6 + 2:i * 6 + 6], byteorder='big')  # 原相位
                    cal_phase = (org_phase % 40000 / 40000) * 360  # 计算后相位
                    cal_cycle = math.floor(org_phase / 40000)  # 周期向下取整

                    uhf_cycle_list.append(cal_cycle)
                    uhf_phase_list.append(cal_phase)
                    uhf_amp_list.append(cal_amp)
                    # uhf_org_phase_list.append(org_phase)

        aa_cycle_list = []
        aa_phase_list = []
        aa_amp_list = []
        aa_org_phase_list = []
        aa_freq = aa_data.get('frequency_aa_ch1')
        if aa_freq > 0:
            byte_cmd = pf.modbus_command(slave_id, 0x05, 0x01, 0x03, 0xFF, 0x00)  # 读取AA谱图
            cli_sk.send(byte_cmd)
            aaatl_data = pf.data_receive(cli_sk)
            logging.debug((device_code, aaatl_data))
            if aaatl_data:
                data_len = int.from_bytes(aaatl_data[5:7], byteorder='big')  # 数据长度
                group_len = (data_len - 9) // 6  # 共多少组数据
                data = aaatl_data[7:data_len - 2]  # 谱图数据
                logging.debug("data recv:" + ''.join(['%02X ' % b for b in data]))
                for i in range(group_len):
                    org_amp = int.from_bytes(data[i * 6 + 0:i * 6 + 2], byteorder='big')  # 原幅值
                    cal_amp = pf.int_to_int16(org_amp) / 10  # todo
                    org_phase = int.from_bytes(data[i * 6 + 2:i * 6 + 6], byteorder='big')  # 原相位
                    cal_phase = (org_phase % 4000 / 4000) * 360  # 计算后相位
                    cal_cycle = math.floor(org_phase / 4000)  # 周期向下取整

                    aa_cycle_list.append(cal_cycle)
                    aa_phase_list.append(cal_phase)
                    aa_amp_list.append(cal_amp)
                    # aa_org_phase_list.append(org_phase)

        byte_cmd = pf.modbus_command(slave_id, 0x01, 0x00, 0x01, 0x00, 0x03)  # 读取报警
        cli_sk.send(byte_cmd)
        recv_data = pf.data_receive(cli_sk)
        logging.debug((device_code, recv_data))
        if recv_data:
            logging.debug((device_code, ''.join(['%02X ' % i for i in recv_data])))
            bin_str = bin(int(recv_data[3]))[2:].zfill(8)
            tev_alarm = int(bin_str[-1])
            uhf_alarm = int(bin_str[-2])
            aa_alarm = int(bin_str[-3])
        else:
            tev_alarm = 0
            uhf_alarm = 0
            aa_alarm = 0
        tev_data['tev_alarm'] = tev_alarm
        tev = {'tev_data': tev_data, 'tev_map': {"tev_phase": tev_phase_list, "tev_cycle": tev_cycle_list,
                                                 "tev_amp": tev_amp_list}}
        uhf_data['uhf_alarm'] = uhf_alarm
        uhf = {'uhf_data': uhf_data, 'uhf_map': {"uhf_phase": uhf_phase_list, "uhf_cycle": uhf_cycle_list,
                                                 "uhf_amp": uhf_amp_list}}
        aa_data['aa_alarm'] = aa_alarm
        aa = {'aa_data': aa_data, 'aa_map': {"aa_phase": aa_phase_list, "aa_cycle": aa_cycle_list, "aa_amp": aa_amp_list}}
        data_1 = {
            "06_data": {
                "aa": aa,
                "tev": tev,
                "uhf": uhf,
            }
        }

        data_2 = {'device_type': device_type, 'device_code': device_code, 'data': json.dumps(data_1)}
        data_dict = {'data_type': 'data', 'data': json.dumps(data_2),
                     'update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        data_json = json.dumps(data_dict)
        logging.debug((device_code, data_json))
        redis_conn.rpush(pf.REDIS_CACHE_KEY, data_json)  # redis插入data数据
        logging.info('[%s]:redis set data success' % device_code)
    else:
        logging.error('[%s]:redis set data fail' % device_code)
